package org.hk.proxy.server.web.interceptor;

import cn.hutool.core.io.FileUtil;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.hk.proxy.common.exception.ApiCommonException;
import org.hk.proxy.server.constant.ProjectConfig;
import org.hk.proxy.server.web.ApiRouteResolve;

import java.io.File;
import java.util.HashSet;
import java.util.Set;

public class UriHttpInterceptor implements HttpInterceptor{
    private  static final Set<String> webPaths = new HashSet<>();
    @Override
    public void preRequest(HttpRequest request) {
        String uri = request.uri();
        uri= request.uri().contains("?")?uri.split("\\?")[0]:uri;
        uri=uri.equalsIgnoreCase("/")?"/index.html":uri;
        if(uri.contains("../")){
            throw new ApiCommonException(HttpResponseStatus.FORBIDDEN.code(),"禁止访问");
        }
        request.setUri(uri);
        if(!webPaths.contains(uri)&& !ApiRouteResolve.containRoute(uri)){
            throw new ApiCommonException(HttpResponseStatus.NOT_FOUND.code(), "Not Found");
        }
    }
    public UriHttpInterceptor() {
        String webPath = ProjectConfig.config.getWebServerConfig().getWebPath();
        recursionWebPaths(new File(webPath),webPath);
    }
    private void recursionWebPaths(File rootFile, String curPath){
        if(FileUtil.isDirectory(curPath)){
            File[] files = FileUtil.ls(curPath);
            for(File file:files){
                if(FileUtil.isDirectory(file)){
                    recursionWebPaths(rootFile,file.getPath());
                }else {
                    webPaths.add(file.getPath().replace(rootFile.getPath(),"").replace(String.valueOf(File.separatorChar),"/"));
                }
            }
        }else {
            webPaths.add(curPath);
        }
    }
    public static Boolean containWebPath(String uri){
        return webPaths.contains(uri);
    }
}
